﻿using System.Configuration;
using System.Data;
using PDFDesign.Dapper;
using PDFDesign.Dapper.Sql;
using PDFDesign.Repository.Builder;

namespace PDFDesign.Repository.Session
{
    /// <summary>
    /// Session 创建类
    /// </summary>
    public class SessionFactory
    {
        /// <summary>
        /// 根据Provider类型，创建数据库连接
        /// </summary>
        /// <returns></returns>
        private static IDbConnection CreateConnectionByProvider()
        {
            var connStr = ConfigurationManager.ConnectionStrings["ConnStr"];
            IDbConnectionBuilder builder = null;
            SqlDialectBase sqlDialect = null;
            switch (connStr.ProviderName)
            {
                case "System.Data.SqlClient":
                    builder = new MSSQLDbConnectionBuilder(connStr.ConnectionString);
                    sqlDialect = new SqlServerDialect();
                    break;
                case "MySql.Data.MySqlClient":
                    builder = new MYSQLDbConnectionBuilder(connStr.ConnectionString);
                    sqlDialect = new MySqlDialect();
                    break;
                case "PostgreSQL":
                    //builder = new PGSQLDbConnectionBuilder(connStr.ConnectionString);
                    //sqlDialect = new PostgreSqlDialect();
                    break;
                default:
                    // 数据库支持拓展
                    break;
            }
            DapperExtensions.SqlDialect = sqlDialect;
            return builder.DbConnection;
        }

        /// <summary>
        /// 创建数据库连接
        /// </summary>
        /// <returns></returns>
        public static IDbConnection CreateConnection()
        {
            IDbConnection conn = CreateConnectionByProvider();

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            return conn;
        }

        /// <summary>
        /// 创建数据库连接会话
        /// </summary>
        /// <returns></returns>
        public static IDbSession CreateSession()
        {
            IDbConnection conn = CreateConnection();
            IDbSession session = new DbSession(conn);

            return session;
        }

        /// <summary>
        /// 创建数据库事务会话
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        /// <returns></returns>
        public static IDbSession CreateSession(IDbConnection conn, IDbTransaction trans)
        {
            IDbSession session = new DbSession(conn, trans);
            return session;
        }
    }
}
